package com.zheng.umbrella.web.controller.manage;

import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.CsvUtils;
import com.zheng.common.util.DateUtil;
import com.zheng.common.util.PropertiesUtil;
import com.zheng.common.util.StringUtil;
import com.zheng.umbrella.common.constant.UmbrellaConstant;
import com.zheng.umbrella.common.constant.UmbrellaResult;
import com.zheng.umbrella.common.constant.UmbrellaResultConstant;
import com.zheng.umbrella.dao.model.*;
import com.zheng.umbrella.dao.use.model.UmbrellaBatchUpdate;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareApiService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareUmbrellaService;
import com.zheng.upms.dao.model.UpmsDict;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2018/9/16.
 */
@Controller
@Api(value = "雨伞管理", description = "雨伞管理")
@RequestMapping("/manage/umbrella")
public class UmbrellaHardwareUmbrellaController extends BaseController {


    private static final Logger LOGGER = LoggerFactory.getLogger(UmbrellaHardwareUmbrellaController.class);

    @Autowired
    private UmbrellaHardwareUmbrellaService umbrellaHardwareUmbrellaService;

    @Autowired
    private UpmsApiService upmsApiService;
    @Autowired
    UpmsDictService upmsDictService;

    @Autowired
    private UmbrellaHardwareApiService umbrellaHardwareApiService;

    @ApiOperation(value = "雨伞首页")
    @RequiresPermissions("umbrella:umbrella:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/umbrella/index.jsp";
    }

    @ApiOperation(value = "雨伞列表")
    @RequiresPermissions("umbrella:umbrella:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order,
            @RequestParam(required = false, value = "type") Integer type,
            @RequestParam(required = false, value = "batchCode") String batchCode,
            @RequestParam(required = false, value = "machineCode") String machineCode,
            @RequestParam(required = false, value = "chipNumber") String chipNumber) {
        UmbrellaHardwareUmbrellaExample umbrellaHardwareUmbrellaExample = new UmbrellaHardwareUmbrellaExample();

        UmbrellaHardwareUmbrellaExample.Criteria criteria = umbrellaHardwareUmbrellaExample.createCriteria();
        criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            umbrellaHardwareUmbrellaExample.setOrderByClause(sort + " " + order);
        }
        if (StringUtils.isNotBlank(search)) {
            criteria.andChipNumberLike("%" + search + "%");
        }
        if (type!=null) {
            criteria.andTypeEqualTo(type);
        }
        if (StringUtils.isNotBlank(batchCode)) {
            criteria.andBatchCodeEqualTo(batchCode);
        }
        if (StringUtils.isNotBlank(machineCode)) {
            criteria.andMachineCodeEqualTo(machineCode);
        }
        if (StringUtils.isNotBlank(chipNumber)) {
            criteria.andChipNumberEqualTo(chipNumber);
        }

        Integer agentId = upmsApiService.selectUserAgentIdByUsername(getLoginUserName());
        if(agentId != null){
            criteria.andAgentIdEqualTo(agentId);
        }

        List<UmbrellaHardwareUmbrella> rows = umbrellaHardwareUmbrellaService.selectByExampleForOffsetPage(umbrellaHardwareUmbrellaExample, offset, limit);
        long total = umbrellaHardwareUmbrellaService.countByExample(umbrellaHardwareUmbrellaExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "批量新增雨伞")
    @RequiresPermissions("umbrella:umbrella:create")
    @RequestMapping(value = "/batchCreate", method = {RequestMethod.GET})
    public String batchCreate(ModelMap modelMap) {
        return "/manage/umbrella/batchCreate.jsp";
    }

    @ApiOperation(value = "批量新增雨伞")
    @RequiresPermissions("umbrella:umbrella:create")
    @RequestMapping(value = "/batchCreate", method = {RequestMethod.POST})
    @ResponseBody
    public UmbrellaResult batchCreate(@RequestParam(value = "file") MultipartFile file) {
        String path = PropertiesUtil.getInstance().getValue(UmbrellaConstant.UPLOAD_FILE_PATH)+"umbrella";
        File f = new File(path);
        if(!f.exists())
            f.mkdirs();
        String fileName = "upload_"+ UUID.randomUUID()+".csv";
        f = new File(path+"/"+fileName);
        if(!f.exists())
            try {
                f.createNewFile();
                file.transferTo(f);
            } catch (IOException e) {
                return new UmbrellaResult(UmbrellaResultConstant.FAILED,"文件创建失败。");
            }
//        CommonsMultipartFile cf= (CommonsMultipartFile)file;
//        DiskFileItem fi = (DiskFileItem)cf.getFileItem();
//        File f = fi.getStoreLocation();
//        FileUtil.copy(fe,f);

        Integer count = CsvUtils.getFileLineCount(f);
        if(count>501) return new UmbrellaResult(UmbrellaResultConstant.FAILED,"一次导入最多500条数据。");

        List<String> dataList = CsvUtils.importCsv(f, 2, 501);
        List<UmbrellaHardwareUmbrella> umbrellas = new ArrayList<UmbrellaHardwareUmbrella>();
        try {
            Date  nowTime = DateUtil.getDate();
            String userName = getLoginUserName();
            Integer agentId = upmsApiService.selectUserAgentIdByUsername(userName);
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String isDefaultCurAgent = request.getParameter("defaultCurAgent");
            long ctime = System.currentTimeMillis();
            for(String d : dataList) {
                String[] data = d.split(",",-1);
                UmbrellaHardwareUmbrella umbrella = new UmbrellaHardwareUmbrella();
                umbrella.setChipNumber(StringUtil.getString(data[0],null));
                umbrella.setType(StringUtil.getInteger(upmsDictService.queryDataDictValueByText(UmbrellaConstant.UM_UMBRELLA_TYPE,StringUtil.getString(data[1],""))));
                umbrella.setCode(StringUtil.getString(data[0],null));
                umbrella.setBatchCode(StringUtil.getString(data[2],null));
                umbrella.setName(StringUtil.getString(data[3],null));
                umbrella.setMachineCode(StringUtil.getString(data[4],null));
                umbrella.setCostprice(StringUtil.getBigDecimal(data[5]));
                umbrella.setMarketprice(StringUtil.getBigDecimal(data[6]));
                umbrella.setDescription(StringUtil.getString(data[7],null));
                umbrella.setFlag(Constant.CONST_FLAG_NORMAL);
                umbrella.setCurrentMachineCode(StringUtil.getString(data[4],null));
                umbrella.setUstatus(2);
                umbrella.setRentingCount(0);
                if("1".equals(isDefaultCurAgent)) {
                    umbrella.setAgentId(agentId);
                }
                umbrella.setCuser(userName);
                umbrella.setCtime(ctime);
                umbrellas.add(umbrella);
            }
            umbrellaHardwareApiService.insertBatch(umbrellas);
        } catch (RuntimeException e) {
            LOGGER.error("存在错误数据，批量导入失败。",e);
            String message = e.getMessage();
            if(message != null && message.contains("Duplicate entry")){
                return new UmbrellaResult(UmbrellaResultConstant.FAILED,"存在重复数据，导入失败。" + message.substring(message.indexOf("Duplicate entry"),message.indexOf("for key 'uk_chip_number'")));
            } else {
                return new UmbrellaResult(UmbrellaResultConstant.FAILED,"存在错误数据，批量导入失败。");
            }
        } catch (Exception e1) {
            LOGGER.error("存在错误数据，批量导入失败。",e1);
            return new UmbrellaResult(UmbrellaResultConstant.FAILED,"存在错误数据，批量导入失败。");
        }

        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS,"批量导入雨伞成功。");
    }

    @ApiOperation(value = "批量更新伞码")
    @RequiresPermissions("umbrella:umbrella:update")
    @RequestMapping(value = "/batchUpdate", method = {RequestMethod.GET})
    public String batchUpdate(ModelMap modelMap) {
        return "/manage/umbrella/batchUpdate.jsp";
    }

    @ApiOperation(value = "批量更新伞码")
    @RequiresPermissions("umbrella:umbrella:update")
    @RequestMapping(value = "/batchUpdate", method = {RequestMethod.POST})
    @ResponseBody
    public UmbrellaResult batchUpdate(@RequestParam(value = "file") MultipartFile file) {
//        CommonsMultipartFile cf= (CommonsMultipartFile)file;
//        DiskFileItem fi = (DiskFileItem)cf.getFileItem();
//        File f = fi.getStoreLocation();
        String path = PropertiesUtil.getInstance().getValue(UmbrellaConstant.UPLOAD_FILE_PATH)+"umbrella";
        File f = new File(path);
        if(!f.exists())
            f.mkdirs();
        String fileName = "upload_"+ UUID.randomUUID()+".csv";
        f = new File(path+"/"+fileName);
        if(!f.exists())
            try {
                f.createNewFile();
                file.transferTo(f);
            } catch (IOException e) {
                return new UmbrellaResult(UmbrellaResultConstant.FAILED,"文件创建失败。");
            }
        Integer count = CsvUtils.getFileLineCount(f);
        if(count>501) return new UmbrellaResult(UmbrellaResultConstant.FAILED,"一次更新最多500条数据。");

        String userName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(userName);

        List<String> dataList = CsvUtils.importCsv(f, 2, 501);
        List<UmbrellaBatchUpdate> umbrellas = new ArrayList<UmbrellaBatchUpdate>();
        try {
            for(String d : dataList) {
                String[] data = d.split(",",-1);
                UmbrellaBatchUpdate umbrellaBatchUpdate = new UmbrellaBatchUpdate();
                umbrellaBatchUpdate.setOldChipNumber(StringUtil.getString(data[0]));
                umbrellaBatchUpdate.setChipNumber(StringUtil.getString(data[1],null));
                umbrellaBatchUpdate.setType(StringUtil.getInteger(upmsDictService.queryDataDictValueByText(UmbrellaConstant.UM_UMBRELLA_TYPE,StringUtil.getString(data[2],""))));
                umbrellaBatchUpdate.setBatchCode(StringUtil.getString(data[3],null));
                umbrellaBatchUpdate.setName(StringUtil.getString(data[4],null));
                umbrellaBatchUpdate.setMachineCode(StringUtil.getString(data[5],null));
                //转小写
                if(umbrellaBatchUpdate.getMachineCode()!=null) {
                    umbrellaBatchUpdate.setMachineCode(umbrellaBatchUpdate.getMachineCode().toLowerCase());
                }
                umbrellaBatchUpdate.setCostprice(StringUtil.getBigDecimal(data[6]));
                umbrellaBatchUpdate.setMarketprice(StringUtil.getBigDecimal(data[7]));
                umbrellaBatchUpdate.setDescription(StringUtil.getString(data[8],null));
                umbrellaBatchUpdate.setAgentId(agentId);
                umbrellas.add(umbrellaBatchUpdate);
            }
            umbrellaHardwareApiService.updateBatch(umbrellas);
        } catch (Exception e) {
            return new UmbrellaResult(UmbrellaResultConstant.FAILED,"存在错误数据，批量更新失败。");
        }

        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS,"批量更新成功。");
    }

    @ApiOperation(value = "新增雨伞")
    @RequiresPermissions("umbrella:umbrella:create")
    @RequestMapping(value = "/create", method = {RequestMethod.GET})
    public String create(ModelMap modelMap) {
        String loginUserName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);
        //伞机
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId);
        List<UmbrellaHardwareMachine> umbrellaHardwareMachineList = umbrellaHardwareApiService.selectMachineByExample(machineExample);
        modelMap.put("machineList", umbrellaHardwareMachineList);
        //批次
        UmbrellaHardwareBatchExample batchExample = new UmbrellaHardwareBatchExample();
        batchExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId);
        List<UmbrellaHardwareBatch> umbrellaHardwareBatchList = umbrellaHardwareApiService.selectBatchByExample(batchExample);
        modelMap.put("batchList", umbrellaHardwareBatchList);
        //雨伞状态
        List<UpmsDict> statusList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_UMBRELLA_STATUS);
        modelMap.put("statusList", statusList);
        //雨伞类型
        List<UpmsDict> typeList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_UMBRELLA_TYPE);
        modelMap.put("typeList", typeList);


        return "/manage/umbrella/create.jsp";
    }

    @ApiOperation(value = "新增雨伞")
    @RequiresPermissions("umbrella:umbrella:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = {RequestMethod.POST})
    public Object create(UmbrellaHardwareUmbrella umbrellaHardwareUmbrella) {
//        ComplexResult result = FluentValidator.checkAll()
//                .on(upmsAgent.getName(), new LengthValidator(1, 120, "名称"))
//                .doValidate()
//                .result(ResultCollectors.toComplex());
//        if (!result.isSuccess()) {
//            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
//        }
        String loginUserName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);
        long time = System.currentTimeMillis();
        umbrellaHardwareUmbrella.setCtime(time);
        umbrellaHardwareUmbrella.setCuser(loginUserName);
        umbrellaHardwareUmbrella.setAgentId(agentId);
        int count = umbrellaHardwareUmbrellaService.insertSelective(umbrellaHardwareUmbrella);
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "删除雨伞")
    @RequiresPermissions("umbrella:umbrella:delete")
    @RequestMapping(value = "/delete/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
//        int count = umbrellaHardwareUmbrellaService.deleteByPrimaryKeys(ids);
        int count = umbrellaHardwareUmbrellaService.deleteLogicByPrimaryKeys(ids,UmbrellaHardwareUmbrella.class,null);
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改雨伞")
    @RequiresPermissions("umbrella:umbrella:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.GET})
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        String loginUserName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);
        //伞机
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId);
        List<UmbrellaHardwareMachine> umbrellaHardwareMachineList = umbrellaHardwareApiService.selectMachineByExample(machineExample);
        modelMap.put("machineList", umbrellaHardwareMachineList);
        //批次
        UmbrellaHardwareBatchExample batchExample = new UmbrellaHardwareBatchExample();
        batchExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId);
        List<UmbrellaHardwareBatch> umbrellaHardwareBatchList = umbrellaHardwareApiService.selectBatchByExample(batchExample);
        modelMap.put("batchList", umbrellaHardwareBatchList);
        //雨伞状态
        List<UpmsDict> statusList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_UMBRELLA_STATUS);
        modelMap.put("statusList", statusList);
        //雨伞类型
        List<UpmsDict> typeList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_UMBRELLA_TYPE);
        modelMap.put("typeList", typeList);

        UmbrellaHardwareUmbrella umbrellaHardwareUmbrella = umbrellaHardwareUmbrellaService.selectByPrimaryKey(id);
        modelMap.put("umbrellaHardwareUmbrella", umbrellaHardwareUmbrella);
        return "/manage/umbrella/update.jsp";
    }

    @ApiOperation(value = "修改雨伞")
    @RequiresPermissions("umbrella:umbrella:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object update(@PathVariable("id") Integer id, UmbrellaHardwareUmbrella umbrellaHardwareUmbrella) {
//        ComplexResult result = FluentValidator.checkAll()
//                .on(upmsAgent.getName(), new LengthValidator(1, 20, "名称"))
//                .doValidate()
//                .result(ResultCollectors.toComplex());
//        if (!result.isSuccess()) {
//            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
//        }
        umbrellaHardwareUmbrella.setId(id);
        int count = umbrellaHardwareUmbrellaService.updateByPrimaryKeySelective(umbrellaHardwareUmbrella);
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }


}
